package com.speily.current.volatileTest;

/**
 * @Auther: SPL
 * @Date: 2019-08-05 11:52
 * @Description: - volatile关键字测试线程类，在volatile变量的控制之下。
 *  volatile作用于变量，保证变量在多个线程间可见（可见性）
 */
public class RunThreadUnderCtrl extends Thread{

//    private boolean isRunning = true;//针对当前线程可见

    volatile private boolean isRunning = true;//针对所有线程可见

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    @Override
    public void run() {

        //通过变量isRunning控制逻辑

        System.out.println("进入到run方法中了");
        while (isRunning == true) {
            System.out.println(Thread.currentThread().getName() + ": 变量isRunning = "+ isRunning);
        }
        System.out.println("线程执行完成了，此时变量isRunning= "  + isRunning);
    }
}

class Run {
    public static void main(String[] args) {

        //创建线程thread。使用变量isRunning控制

        try {
            RunThreadUnderCtrl thread = new RunThreadUnderCtrl();
            thread.start();
            Thread.sleep(1000);//main线程休眠1s
            thread.setRunning(false);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
